package com.wanpinghui.supplier.business;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.business.view.AndroidBug5497Workaround;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/2/27
 * 版本:1.0
 ***/
@ContentView(R.layout.layout_activity_input_bullet_screen)
public class InputActivity extends BaseActivity {
    @ViewInject(R.id.tv_send)
    private TextView mTextViewSend;
    @ViewInject(R.id.edt_input)
    private EditText mEditTextInput;
    @ViewInject(R.id.ll_root)
    private LinearLayout mLayoutRoot;
    @ViewInject(R.id.ll_input)
    private LinearLayout mLayoutInput;
    private static final String EXTRA_TEXT = "extra_text";
    public final static int REQ_CODE = 20;
    private int keyboardOldHeight = -1;
    private int keyboardNowHeight = -1;
    private boolean sendResult = false;
    private String hint;

    // callback
    public interface InputActivityProxy {
        void onSendMessage(String text);
        void onSofeInputSize(int currentSize);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        finish();
    }

    public static void start(Activity context, String text, InputActivityProxy proxy) {
        InputActivityProxyManager.getInstance().setProxy(proxy);

        Intent intent = new Intent();
        intent.putExtra(EXTRA_TEXT, text);
        intent.setClass(context, InputActivity.class);
        context.startActivityForResult(intent, REQ_CODE);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(0, 0);
    }

    @Override
    public String getName() {
        return InputActivity.class.getName();
    }

    @Override
    public boolean isHideBoa() {
        return false;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mEditTextInput.setFocusable(true);
        mEditTextInput.setFocusableInTouchMode(true);
        mEditTextInput.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditTextInput, 0);
    }

    /**
     * 监听键盘收起事件，键盘收起，则该Activity finish
     */
    private void setInputListener() {
        mLayoutRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int screenHeight = getScreenHeight();
                keyboardNowHeight = screenHeight - r.bottom - getNavigationBarHeight();
                if (keyboardOldHeight != -1 && keyboardNowHeight != keyboardOldHeight && keyboardNowHeight <= 0) {
                    // 只适用于没有表情和更多布局的修改
                    //setActivityResult(MODE_KEYBOARD_COLLAPSE);
                    doFinish();
                }else {
//                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mLayoutInput.getLayoutParams();
//                    lp.setMargins(0, 0, 0, getNavigationBarHeight());
//                    mLayoutInput.requestLayout();
                    if (keyboardNowHeight > 100 && InputActivityProxyManager.getInstance().getProxy() != null && !sendResult) {
                        sendResult = true;
                        InputActivityProxyManager.getInstance().getProxy().onSofeInputSize(keyboardNowHeight);
                    }
                    keyboardOldHeight = keyboardNowHeight;
                }

            }
        });
    }

    private int getNavigationBarHeight() {
        if (checkDeviceHasNavigationBar(InputActivity.this)) {
            Resources resources = getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        }else {
            return 0;
        }
        //LogUtils.w("InputActivity", "navigationbar height is : " +height);
        //return height;
    }

    @SuppressLint("NewApi")
    public static boolean checkDeviceHasNavigationBar(Context activity) {

        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        return !hasMenuKey && !hasBackKey;
    }

    private void resetSendMsgRl(){

        final View decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                Rect rect= new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int screenHeight = getScreenHeight();
                int heightDifferent = screenHeight - rect.bottom;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mEditTextInput.getLayoutParams();
                lp.setMargins(0, 0, 0, heightDifferent);
                mEditTextInput.requestLayout();
            }
        });
    }


    private int getScreenHeight(){
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int height = outMetrics.heightPixels;
        return  height;
    }

    @Override
    public void initViews() {
        AndroidBug5497Workaround.assistActivity(this);
    }

    @Override
    public void bindEvents() {
        setInputListener();
        mTextViewSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isNotEmpty(mEditTextInput.getText().toString().trim())) {
                    if (InputActivityProxyManager.getInstance().getProxy() != null) {
                        InputActivityProxyManager.getInstance().getProxy().onSendMessage(mEditTextInput.getText().toString());
                        mEditTextInput.setText("");
                        hideInputMethod();
                    }
                }else {
                    ToastManager.getInstance().showToast("请输入内容");
                    mEditTextInput.setText("");
                }
            }
        });
        findViewById(R.id.view_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputMethod();
            }
        });
    }

    @Override
    public void initData() {
        if (getIntent() != null) {
            hint = getIntent().getStringExtra(EXTRA_TEXT);
            mEditTextInput.setHint(hint);
        }
        int statusBarHeight = DevicesUtil.getStatusBarHeight(this);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mLayoutInput.getLayoutParams();
        layoutParams.bottomMargin = statusBarHeight;
        mLayoutInput.setLayoutParams(layoutParams);
    }


    /**
     * 收起键盘，返回调用Activity
     */
    private void setActivityResult(final int mode) {
        // hide keyboard
        hideInputMethod();

        // return result to pre activity
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TEXT, mEditTextInput.getText().toString());
        setResult(Activity.RESULT_OK, intent);
    }

    private void hideInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditTextInput.getWindowToken(), 0);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mLayoutInput.setVisibility(View.GONE);
            finish();
        }
    }

    private Handler handler = new Handler(){};

    private void doFinish() {
        if (InputActivityProxyManager.getInstance().getProxy() != null) {
            sendResult = false;
            InputActivityProxyManager.getInstance().getProxy().onSofeInputSize(0);
        }
        // 解决返回到上一个页面，上个页面的键盘没有收起（依然能看到输入框处于挤压状态）的问题。
        handler.postDelayed(new Runnable() {
            //            @Override
            public void run() {
                finish();
                // 解决部分小米手机，在Theme中设置android:windowAnimationStyle指向null无效的问题。
                overridePendingTransition(0, 0);
            }
        }, 50);
    }

    private static class InputActivityProxyManager {
        private InputActivityProxy proxy;

        public static InputActivityProxyManager getInstance() {
            return InstanceHolder.instance;
        }

        public void setProxy(InputActivityProxy proxy) {
            this.proxy = proxy;
        }

        public InputActivityProxy getProxy() {
            return proxy;
        }

        public void clearProxy() {
            this.proxy = null;
        }

        static class InstanceHolder {
            final static InputActivityProxyManager instance = new InputActivityProxyManager();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //InputActivityProxyManager.getInstance().clearProxy();
    }

    @Override
    public void onBackPressed() {
        doFinish();
    }
}
